package com.forfunnet.minjian.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.widget.EditText;
import android.widget.TextView;

import com.forfunnet.minjian.R;
import com.forfunnet.minjian.consts._3rdKey;
import com.forfunnet.minjian.message.request.ChangePasswordRequest;
import com.forfunnet.minjian.message.response.BaseResponse;
import com.forfunnet.minjian.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by RexQian on 4/3/16.
 */
@EActivity(R.layout.activity_password)
public class PasswordActivity extends BaseActivity {
    private static final int RETRY_INTERVAL = 60;
    private int mRetryTime = RETRY_INTERVAL;

    private static final int EVENT_RETRY_COUNTER = 1;

    @Bean
    ActivityHelper mActivityHelper;

    private EventHandler mSmsHandler = new EventHandler() {
        public void afterEvent(final int event, final int result, final Object data) {
            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    afterSendVerificationCode(true);
                }
                else {
                    afterSendVerificationCode(false);
                }
            }
        }
    };

    @ViewById(R.id.editAccount)
    EditText mEditAccount;

    @ViewById(R.id.editPassword)
    EditText mEditPassword;

    @ViewById(R.id.editConfirmPassword)
    EditText mEditConfirmPassword;

    @ViewById(R.id.editVerificationCode)
    EditText mEditVerificationCode;

    @ViewById(R.id.btnSendVerificationCode)
    TextView mBtnSendVerificationCode;

    @ViewById(R.id.btnConfirm)
    TextView mBtnConfirm;

    @Click(R.id.btn_back)
    void onBackButtonClick() {
        setResult(RESULT_CANCELED);
        finish();
    }

    @AfterViews
    void afterView() {
        SMSSDK.initSDK(this, _3rdKey.ShareSdk.APPKEY, _3rdKey.ShareSdk.APPSECRET);
    }

    @Override
    public void onStart() {
        super.onStart();

        SMSSDK.registerEventHandler(mSmsHandler);
    }

    @Override
    public void onStop() {
        SMSSDK.unregisterEventHandler(mSmsHandler);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(EVENT_RETRY_COUNTER);
    }

    @Click(R.id.btnSendVerificationCode)
    void sendConfirmCode() {
        String account = mEditAccount.getText().toString();
        if (account.isEmpty()) {
            mActivityHelper.showShortToast(getString(R.string.account_empty));
            mEditAccount.requestFocus();
            return;
        }
        boolean isPhoneNumber = CommonUtils.isValidPhoneNumber(account);

        if (!isPhoneNumber) {
            mActivityHelper.showShortToast(getString(R.string.account_format_error));
            mEditAccount.requestFocus();
            return;
        }
        SMSSDK.getVerificationCode("86", account);

        mBtnSendVerificationCode.setText(String.format(getString(R.string.verification_code_retry), RETRY_INTERVAL));
        mBtnSendVerificationCode.setEnabled(false);
        mHandler.sendEmptyMessageDelayed(EVENT_RETRY_COUNTER, 1000);
    }

    @Click(R.id.btnConfirm)
    void onConfirm() {
        String account = mEditAccount.getText().toString();
        if (account.isEmpty()) {
            mActivityHelper.showShortToast(getString(R.string.account_empty));
            mEditAccount.requestFocus();
            return;
        }
        boolean isPhoneNumber = CommonUtils.isValidPhoneNumber(account);
        boolean isEmailAddress = CommonUtils.isValidEmail(account);

        if (!isPhoneNumber && !isEmailAddress) {
            mActivityHelper.showShortToast(getString(R.string.account_format_error));
            mEditAccount.requestFocus();
            return;
        }

        String verificationCode = mEditVerificationCode.getText().toString();
        if (verificationCode.isEmpty()) {
            mActivityHelper.showShortToast(getString(R.string.hint_verification_code));
            mEditVerificationCode.requestFocus();
            return;
        }

        String password = mEditPassword.getText().toString();
        if (password.isEmpty()) {
            mActivityHelper.showShortToast(getString(R.string.hint_new_password));
            mEditPassword.requestFocus();
            return;
        }

        String confirmPassword = mEditConfirmPassword.getText().toString();
        if (confirmPassword.isEmpty()) {
            mActivityHelper.showShortToast(getString(R.string.password_not_match));
            mEditConfirmPassword.requestFocus();
            return;
        }

        if (!password.equals(confirmPassword)) {
            mActivityHelper.showShortToast(getString(R.string.password_not_match));
            mEditConfirmPassword.requestFocus();
            return;
        }
        mActivityHelper.showLoadingDialog(getString(R.string.change_password_wait));
        changePassword(account, password, verificationCode);
    }


    @UiThread
    void afterSendVerificationCode(boolean success) {
        if (success) {
            mActivityHelper.showShortToast(getString(R.string.sms_verification_code_sent));
        }
        else {
            mActivityHelper.showShortToast(getString(R.string.sms_verification_code_send_error));
            restoreVerificationButton();
        }
    }

    @Background
    void changePassword(String account, String password, String verifyCode) {
        ChangePasswordRequest request = new ChangePasswordRequest();
        request.Phone = account;
        request.NewPassword = password;
        request.VerifyCode = verifyCode;
        BaseResponse response = mApp.restClient().changePassword(request);
        AfterChangePassword(response);
    }

    @UiThread
    void AfterChangePassword(BaseResponse response) {
        mActivityHelper.dismissLoadingDialog();
        if (BaseResponse.hasError(response)) {
            mActivityHelper.showShortToast(BaseResponse.getErrorMessage(response));
        }
        else {
            mActivityHelper.showShortToast(getString(R.string.change_password_success));
            finish();
        }
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == EVENT_RETRY_COUNTER) {
                mRetryTime--;
                if (mRetryTime == 0) {
                    restoreVerificationButton();
                    mRetryTime = RETRY_INTERVAL;
                } else {
                    mBtnSendVerificationCode.setText(String.format(getString(R.string.verification_code_retry), mRetryTime));
                    mHandler.sendEmptyMessageDelayed(EVENT_RETRY_COUNTER, 1000);
                }
            }
        }
    };

    private void restoreVerificationButton() {
        mHandler.removeMessages(EVENT_RETRY_COUNTER);
        mBtnSendVerificationCode.setText(R.string.send_verification_code);
        mBtnSendVerificationCode.setEnabled(true);
    }
}
